package cn.coufran.springboot.starter.http;

import com.alibaba.fastjson2.JSON;

import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Flow;
import java.util.function.Function;

public class BodySubscribers {
    public static <T> HttpResponse.BodySubscriber<T> ofJson(Class<T> clazz) {
        return new BodySubscriber<>(
                bytes -> JSON.parseObject(bytes, clazz)
        );
    }

    private static class BodySubscriber<T> implements HttpResponse.BodySubscriber<T> {
        private final HttpResponse.BodySubscriber<byte[]> subscriber = HttpResponse.BodySubscribers.ofByteArray();
        private final Function<byte[], T> finisher;

        private BodySubscriber(Function<byte[], T> finisher) {
            this.finisher = finisher;
        }

        @Override
        public void onSubscribe(Flow.Subscription subscription) {
            subscriber.onSubscribe(subscription);
        }

        @Override
        public void onNext(List<ByteBuffer> item) {
            subscriber.onNext(item);
        }

        @Override
        public void onError(Throwable throwable) {
            subscriber.onError(throwable);
        }

        @Override
        public void onComplete() {
            subscriber.onComplete();
        }

        @Override
        public CompletionStage<T> getBody() {
            return subscriber.getBody().thenApply(finisher);
        }


    }
}
